package random.fox.p2p.ui.customview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.text.style.DynamicDrawableSpan;
import android.view.View;
import android.widget.TextView;

/**
 * 自定义的一个span,用来显示标记
 * Created by wq on 15/3/22.
 */
public class TagSpan extends DynamicDrawableSpan {

    String[] colors = new String[]{
        "#6095d6","#b27fda","#2b7594","#acb8a0","#bfe893"
    };

    Context context;
    String source;
    public TagSpan(Context context, String source) {
        this.source = source;
        this.context = context;
    }

    @Override
    public Drawable getDrawable() {
        return convertViewToDrawable(createContactTextView(context,source));
    }

    public TextView createContactTextView(Context context, String text) {
        TextView tv = new TextView(context);
        float[] outerR = new float[] { 10, 10, 10, 10, 10, 10, 10, 10 };
        RoundRectShape shape = new RoundRectShape(outerR,null,null); //圆角矩形的绘制
        ShapeDrawable drawable = new ShapeDrawable(shape);
        int index = (int) (System.currentTimeMillis()%colors.length);
        drawable.getPaint().setColor(Color.parseColor(colors[index]));
        tv.setBackgroundDrawable(drawable);
        tv.setText(text);
        tv.setPadding(20,5,20,5);
        tv.setTextColor(Color.WHITE);
        tv.setTextSize(35);
        return tv;
    }


    private BitmapDrawable convertViewToDrawable(View view) {
        int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(spec, spec);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        Bitmap b = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        c.translate(-view.getScrollX(), -view.getScrollY());
        view.draw(c);
        view.setDrawingCacheEnabled(true);
        Bitmap cacheBmp = view.getDrawingCache();
        Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
        view.destroyDrawingCache();
        BitmapDrawable bitmapDrawable = new BitmapDrawable(viewBmp);
        bitmapDrawable.setBounds(0,0,bitmapDrawable.getIntrinsicWidth(),bitmapDrawable.getIntrinsicHeight());
        return bitmapDrawable;
    }

    /**
     * 获得span的内容
     * @return
     */
    public String getSource(){
        return source;
    }
}
